
package com.joysuch.wwyt.core.controller;

import cn.zlg.common.springmvc.validate.constraints.NotNull;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.joysuch.wwyt.core.bean.*;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.entity.BaseLoginAccount;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.repository.BaseLoginAccountDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.security.ShiroUser;
import com.joysuch.wwyt.core.service.AuthorityService;
import com.joysuch.wwyt.workflow.bean.WorkFlowTaskListBean;
import com.joysuch.wwyt.workflow.service.WorkFlowDocService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Hex;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Controller
@RequestMapping("/base/authority")
@Api(tags = "系统管理-用户权限")
public class AuthorityController {

    @Autowired
    private AuthorityService authorityService;
    @Autowired
    private WorkFlowDocService workFlowDocService;
    @Autowired
    private BaseLoginAccountDao baseLoginAccountDao;
    @Autowired
    private BaseUserDao baseUserDao;

    @RequestMapping("add-or-update-menu")
    @ResponseBody
    public ResultBean addMenu(@Valid BaseMenuFunctionEditBean bean) {
        authorityService.addOrUpdateMenu(bean);
        return ResultBean.success("添加成功");
    }

    @RequestMapping("query-menu-by-name")
    @ResponseBody
    public ResultBean queryMenuDetailByName(@Valid @NotNull(field = "名称") String name, boolean exactMatch) {
        return ResultBean.success(authorityService.queryMenuByName(name, exactMatch));
    }

    @RequestMapping("query-for-edit")
    @ResponseBody
    public ResultBean queryForEdit(@Valid @NotNull(field = "角色") Long roleId) {
        List<AuthorityBean> list = authorityService.queryForEditByRoleId(roleId);
        return ResultBean.success(list);
    }

    @RequestMapping("query-user-role-list")
    @ResponseBody
    public ResultBean queryUserRoleList(@Valid @NotNull(field = "用户ID") Long userId) {
        List<SimpleSelectListBean> list = authorityService.queryForUserRoleList(userId);
        return ResultBean.success(list);
    }

    @RequestMapping("top-menus")
    @ResponseBody
    public ResultBean getTopMenus() {
        return ResultBean.success(authorityService.queryForTopMenu());
    }

    @RequestMapping("update")
    @ResponseBody
    public ResultBean updateAuthority(Long roleId, String authority) {
        Assert.isTrue(roleId != null, "jobId,userId不能同时为空");
        Gson gson = new Gson();
        List<AuthorityBean> list = gson.fromJson(authority, new TypeToken<List<AuthorityBean>>() {
        }.getType());
        authorityService.updateAuthority(roleId, null, list);
        return ResultBean.success("更新权限成功");
    }

    @RequestMapping("update-user-role")
    @ResponseBody
    public ResultBean updateUserRole(@RequestBody UserAssignRoleBean bean) {
        authorityService.updateUserRoles(bean);
        return ResultBean.success("更新权限成功");
    }

    /**
     * 获取当前用户的身份、权限信息
     *
     * @return
     */
    @RequestMapping("get-info")
    @ResponseBody
    public ResultBean getInfo(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        ShiroUser user = (ShiroUser) subject.getPrincipal();
        UserInfoBean bean = new UserInfoBean();
        bean.setId(user.getRealUserId());
        bean.setCompany(user.getCompanyName());
        bean.setCompanyId(user.getCompanyId());
        bean.setCompanyCode(user.getCompanyCode());
        bean.setTenentId(user.getTenentId());
        bean.setJobId(user.getJobId());
        bean.setJobName(user.getJobName());
        bean.setName(user.getUsername());
        bean.setRealName(user.getRealName());
        bean.setDepartId(user.getDepartId());
        bean.setDepartName(user.getDepartName());
        bean.setUserCode(user.getCode());
        //设置第一次登录字段
        Long realUserId = user.getRealUserId();
        Optional<BaseUser> byId = baseUserDao.findById(realUserId);
        if (!byId.isPresent()) {
            return ResultBean.success("登陆用户不存在");
        }
        BaseUser baseUser = byId.get();
        BaseLoginAccount baseLoginAccount = baseLoginAccountDao.findByBaseUser(baseUser);
        if (Objects.isNull(baseLoginAccount)) {
            return ResultBean.success("登陆用户不存在");
        }
        Integer firstLogin = baseLoginAccount.getFirstLogin();
        bean.setFirstLogin(firstLogin);

        List<AuthorityBean> authList = authorityService.queryAuthorityByUserId(user.getRealUserId(),
                user.isSuperAdmin());

        bean.setAuth(authList);

        return ResultBean.success(bean);
    }

    @RequestMapping("query-system-list")
    @ResponseBody
    public ResultBean querySystemList() {

        List<SimpleSelectListBean> list = authorityService.selectSystemList();
        return ResultBean.success(list);
    }

    @RequestMapping("query-dashboard-list")
    @ResponseBody
    public ResultBean queryDashboardList() {
        List<DashboardMenuBean> list = authorityService.queryDashboardList();
        return ResultBean.success(list);
    }

    @PostMapping("role-update-users")
    @RequiresPermissions("base:authority:role-update-users")
    @ResponseBody
    public ResultBean roleUpdateUsers(@RequestBody BaseRoleAddUserBean roleAddUserBean) {
        authorityService.roleUpdateUsers(roleAddUserBean);
        return ResultBean.defaultSuccessResult();
    }

    @PostMapping("role-user-list")
    @ResponseBody
    public ResultBean roleUserList(@RequestBody BaseUserRoleListSearchBean bean) {
        return authorityService.roleUserList(bean);
    }

    @PostMapping("/v2/role-user-list")
    @ApiOperation(value = "获取全部用户id")
    @ResponseBody
    public ResultBean newRoleUserList(@RequestBody BaseUserRoleListSearchBean bean) {
        return authorityService.newRoleUserList(bean);
    }


    @RequestMapping("role-user-listAll")
    @ResponseBody
    @ApiOperation(value = "获取用户当前角色的用户列表", response = WorkFlowTaskListBean.class)
    public ResultBean roleUserListAll(Long roleId) {
        return authorityService.roleUserListAll(roleId);
    }

    @RequestMapping("wf-signature")
    @ResponseBody
    public ResultBean signature() {
        String appId = "mvAmIwYJ7x6y0EADQvUb";
        String appSecret = "u0tyPOEZEvWrzC1K4dMvifIvoLOX2wEc";
        String signature = Hex.encodeHexString(digest(appId + appSecret));
        Map<String,Object> signMap =new HashMap<>();
        signMap.put("signature",signature);
        signMap.put("app_id",appId);
        return ResultBean.success(signMap);
    }

    public static byte[] digest(String str) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
            return messageDigest.digest();
        } catch (NoSuchAlgorithmException var3) {
            var3.printStackTrace();
            return null;
        }
    }
}
